﻿using AutoUpdate.Log; 
using ScannerApp.Common;
using ScannerApp.Common.PLC;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using static ScannerApp.Common.PopMessageHelper;

namespace ScannerApp.SingleBusiness
{
    /// <summary>
    /// DilutionPLC.xaml 的交互逻辑
    /// </summary>
    public partial class DilutionPLC : Window
    {

        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();
        IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");
        string Com = "", BaudRate = "", DataBits = "", StopRate = "", ParityRate = "";
        SerialPort sp = new SerialPort();
        private int errorlink = 0;
        bool sftz = false;//是否停止
        bool cansacn = true;
        System.Timers.Timer timer = new System.Timers.Timer();
        int ddzl = 0;
         string ip = "192.168.1.5"; 
        //System.Timers.Timer timer_heartbeat= new System.Timers.Timer();
        System.Windows.Threading.DispatcherTimer timer_heartbeat = new System.Windows.Threading.DispatcherTimer();

        System.Windows.Threading.DispatcherTimer timerelash = new System.Windows.Threading.DispatcherTimer();

        private string strTm1="";

        public DilutionPLC()
        {
            InitializeComponent();
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
               this.WindowState = System.Windows.WindowState.Maximized;
                //this.Left = 0;
                //this.Top = 0;
                //this.Height = SystemParameters.WorkArea.Height + 20;//获取屏幕的宽高  使之不遮挡任务栏
                //this.Width = SystemParameters.WorkArea.Width;
                sysname.Text = publicclass.SystemName;
                czy.Text = publicclass.UserName;
                tm1.Focus();


                string[] s = System.IO.Ports.SerialPort.GetPortNames();
                if (ini.ExistINIFile())
                {
                    string Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                                                                  // string Com =  Common.ConfigHelper.GetIni("Com","");
                    if (s.Length < 1 || Com == "")
                    {
                        //   btndzc.Background = System.Windows.Media.Brushes.Red;
                        errorlink = 0;
                        ComSet wcs = new ComSet();
                        wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        wcs.updateMainwindowLabel += FuncSettingClosed;
                        wcs.ShowDialog();//模式，弹出！

                    }
                    else
                    {
                        UIAction(() =>
                        {
                            GetIni();
                        });
                    }

                }
                else
                {
                    //  btndzc.Background = System.Windows.Media.Brushes.Red;
                }

                CZTM();
                LoadPlc();

                //默认
                bool o = false;
                int m239 = DMTDeltaPLC.ReadMReg(2, out o);
                if (m239 == 1)//操作成功且未启动
                {
                    if (!o)
                    {
                        start.Background = System.Windows.Media.Brushes.Green;
                        start.IsEnabled = true;
                        stop.Background = System.Windows.Media.Brushes.Gray;
                        stop.IsEnabled = false;
                    }
                    else
                    {
                        start.Background = System.Windows.Media.Brushes.Gray;
                        start.IsEnabled = false;
                        stop.Background = System.Windows.Media.Brushes.Red;
                        stop.IsEnabled = true;
                    }

                }
                else
                {
                    start.Background = System.Windows.Media.Brushes.Green;
                    start.IsEnabled = true;
                    stop.Background = System.Windows.Media.Brushes.Gray;
                    stop.IsEnabled = false;
                }

                timer_heartbeat.Interval = TimeSpan.FromSeconds(1);
                timer_heartbeat.Tick += heartbeat;
                timer_heartbeat.Start();

                timerelash.Interval = TimeSpan.FromMilliseconds(200);
                timerelash.Tick += relash;
                timerelash.Start();

            }
            catch (Exception ex)
            {
                loadingEnd();
                PopMessageHelper.ShowMessage("初始化错误"+ex.Message, "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);


            }
            
        }


        //返回时候触发这个函数
        private void FuncSettingClosed(string labelContent)
        {

            string Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                                                          //    string Com = Common.ConfigHelper.GetIni("Com", "");
            if (Com == "" && labelContent == "0")
            {
                PopMessageHelper.ShowMessage("检测没有初始化串口，无法采集信息，请重新设置！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

                ComSet wcs = new ComSet();
                wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                wcs.updateMainwindowLabel += FuncSettingClosed;
                wcs.ShowDialog();//模式，弹出！ 

            }
            else
            {
                UIAction(() =>
                {
                    GetIni();
                });

            }
            //label.Content = labelContent;

        }
        private void GetIni()
        {
            if (ini.ExistINIFile())
            {
                Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                BaudRate = ini.IniReadValue("串口设置", "BaudRate"); //Common.ConfigHelper.GetIni("BaudRate", "");
                DataBits = ini.IniReadValue("串口设置", "DataBits");//Common.ConfigHelper.GetIni("DataBits", "");
                StopRate = ini.IniReadValue("串口设置", "StopRate");//Common.ConfigHelper.GetIni("StopRate", "");
                ParityRate = ini.IniReadValue("串口设置", "ParityRate"); //Common.ConfigHelper.GetIni("ParityRate", "");
            }
            LinkSeriPort();
        }
        void LinkSeriPort()
        {

            try
            {

                //串口设置默认选择项  
                //cbSerial = 0;         
                string PortName = Com;//串口名    默认值第一个
                int BR = int.Parse(BaudRate);//获取或设置串行 波特率bit/s  默认值9600
                int DB = int.Parse(DataBits); ;//获取或设置每个字节的标准数据位长度 默认值8
                StopBits Stop = (StopBits)Convert.ToDouble(StopRate); ;//获取或设置每个字节的标准停止位数    默认值One 

                Parity ParityBits = Parity.None;//获取或设置奇偶校验检查协议    默认值None
                ParityBits = ParityRate == "None" ? Parity.None : Parity.Odd;//目前就2个
                Logger.Instance.WriteLog( "[COM设置]" + PortName+";"+ BaudRate+";"+ DataBits+";"+ StopRate+";"+ ParityRate, LogType.Information, "weight");

                if (sp.IsOpen)//先判断是否打开 
                    sp.Close();
                sp = new SerialPort(PortName, BR, ParityBits, DB, Stop);
                sp.WriteTimeout = 3000;
                sp.ReadTimeout = 3000;
                sp.Open();
                if (!sp.IsOpen)//再判断是否打开成功
                {
                    errorlink++;

                    DispatcherTimer timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(10);
                    timer.Tick += (x, y) =>
                    {
                        LinkSeriPort();
                    };
                    timer.Start();
                    return;
                }
                else
                {
                  //  btndzc.Background = System.Windows.Media.Brushes.Green;

                    errorlink = 0;

                    //UIAction(() =>
                    //{
                    sp.ReceivedBytesThreshold = 1;//接收缓冲区当中如果有一个字节的话就出发接收函数

                    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); //订阅委托
                                                                                            //});
 


                }
            }
            catch (Exception ex)
            {


                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }
        private void sp_DataReceived_old(object sender, SerialDataReceivedEventArgs e)

        {
            try
            {
                Thread.Sleep(100);//发送和接收均为文本时，接收中为加入判断是否为文字的算法，发送你（C4E3），接收可能识别为C4,E3，可用在这里加延时解决

                if (sp.IsOpen)     //此处可能没有必要判断是否打开串口，但为了严谨性，我还是加上了

                {
                    int count = sp.BytesToRead;
                    if (count <= 0 || count <= 6)//发现后面g /r/n会第二次分发
                        return;
                    //Thread.Sleep(10);
                    try
                    {
                        byte[] RS232DataBuff = new byte[count];    //BytesToRead:sp1接收的字符个数 

                        try

                        {

                            Byte[] receivedData = new Byte[sp.BytesToRead];        //创建接收字节数组

                            sp.Read(receivedData, 0, receivedData.Length);         //读取数据                       

                            sp.DiscardInBuffer();    
                            //清空SerialPort控件的Buffer
                        
                            string g_s_Data = "K +   189.2  g";
                            //Byte[] RData = new Byte[16];
                            //}
                          if (receivedData.Length < 15) return;
                            //if (receivedData[0].ToString("X2") != "4B") return;
                            //if (receivedData[receivedData.Length - 1].ToString("X2") != "0D"
                            //    || receivedData[receivedData.Length].ToString("X2") != "0A")
                            //{
                            //    return;
                            //}
                        
                                string strRcv = System.Text.Encoding.Default.GetString(receivedData);
                           // Logger.Instance.WriteLog(strRcv, LogType.Information, "weight");

                             //  Logger.Instance.WriteLog( "[处理前]"+ g_s_Data, LogType.Information, "xsweight");
                            bool sffs = false;
                            if (strRcv.Contains("-")) sffs = true; 
                           string strzl = strRcv.Replace("g", "").Replace(" ", "").Replace("\r\n", "")
                                .Replace("K", "").Replace("*", "").Replace("+", "").Replace("-", "")
                                .Replace("\n", "").Replace("\r", "");
                           // Logger.Instance.WriteLog("处理后："+strzl, LogType.Information, "xsweight");
                            if (StrCount(strzl, ".") > 1) return;
                            float a = 0;
                            try { a = float.Parse(strzl); } catch { }
                            if (strzl != "")
                                UIAction(() =>
                                {//D110
                                     //tips.Text = strRcv ;
                                   // if (a != 0)
                                    {
                                        if (!sffs)
                                            SendPLC32((int)a, 111, 110);
                                        else SendPLC32(-(int)a, 111, 110);
                                    }
                                    // cz.Text = a.ToString();// float.Parse(strzl).ToString();
                                });
                            //SetText(zl);
                            //这里需要解析字符串
                            //正负 空格 数字（10000）.数字（1）单位（2）
                            // cz.Text = "A:"+ g_s_Data+"|B:"+strRcv;
                            // txtReceive.Text += strRcv + "\r\n";

                        }
                        catch (System.Exception ex)
                        {
                            ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                            Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                            return;


                        }
                    }
                    catch (Exception ex)
                    {
                        ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                        Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                        return;

                    }

                }

                else
                {
                    //zt.Text = "串口打开失败！重试:" + errorlink;
                    //zt.Foreground = Brushes.Red;
                    LinkSeriPort();

                }
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }


        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)

        {
            try
            {
                Thread.Sleep(50);//发送和接收均为文本时，接收中为加入判断是否为文字的算法，发送你（C4E3），接收可能识别为C4,E3，可用在这里加延时解决

                if (sp.IsOpen)     //此处可能没有必要判断是否打开串口，但为了严谨性，我还是加上了

                {
                    int count = sp.BytesToRead;
                    if (count <= 0 || count <= 6)//发现后面g /r/n会第二次分发
                        return;
                    //Thread.Sleep(10);
                    try
                    {
                        byte[] RS232DataBuff = new byte[count];    //BytesToRead:sp1接收的字符个数 

                        try

                        {

                            Byte[] receivedData = new Byte[sp.BytesToRead];        //创建接收字节数组

                            sp.Read(receivedData, 0, receivedData.Length);         //读取数据                       

                            sp.DiscardInBuffer();                                  //清空SerialPort控件的Buffer
                            string strRcv = "";
                            string g_s_Data = "";
                            for (int i = 0; i < receivedData.Length; i++) //窗体显示
                            {
                                //if (Convert.ToChar(receivedData[0]).ToString() == "-")
                                //{
                                //    cz.Text = "-";
                                //}
                                //if (i > 0)
                                g_s_Data += Convert.ToChar(receivedData[i]);
                                strRcv += Convert.ToChar(receivedData[i]);
                                //strRcv += receivedData[i].ToString("X2");  //16进制显示 
                            }
                          //  Logger.Instance.WriteLog("[称重]" + strRcv, LogType.Information, "temp");

                            bool sffs = false;
                            if (strRcv.Contains("-")) sffs = true;
                            //+000429 g 
                            //一次获取大于2次，必须选择一个有效
                            try
                            {
                                string strzl = g_s_Data.Split('g')[1];
                             //   Logger.Instance.WriteLog("[逻辑处理]" + strzl, LogType.Information, "temp");
                                string result = System.Text.RegularExpressions.Regex.Replace(strzl, @"[^0-9]+", "");
                            //    Logger.Instance.WriteLog("[处理后]" + result, LogType.Information, "temp");
                                // strzl = g_s_Data.Replace("g", "").Replace(" ", "").Replace("\r\n", "").Replace("+", "").Replace("\n", "").Replace("\r", "");

                                float a = 0;
                                try { a = float.Parse(result); }
                                catch
                                {
                                    return;
                                }
                                if (result != "")
                                    UIAction(() =>
                                    {
                                        if (!sffs)
                                            SendPLC32((int)a, 111, 110);
                                        else SendPLC32(-(int)a, 111, 110);
                                    });
                            }
                            catch { } 
                           

                        }
                        catch (System.Exception ex)
                        {
                            ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                            Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                            return;


                        }
                    }
                    catch (Exception ex)
                    {
                        ScannerApp.Common.AutoClosedMsgBox.Show("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgBoxStyle.RedCritical_OK);
                        Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");
                        return;

                    }

                }

                else
                {
                    //zt.Text = "串口打开失败！重试:" + errorlink;
                    //zt.Foreground = Brushes.Red;
                    LinkSeriPort();

                }
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }


        private int StrCount(string str, string constr)
        {
            int c = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i].ToString() == constr)
                {
                    c++;
                }
            }
            return c;
      }

        private void relash(object source, EventArgs e)
        {
            reflashData();//刷新铜重，稳定，获取停止
        }
            
               int clcs = 1;
        private   void heartbeat(object source,  EventArgs e)
        {

            try
            {
                double result = 0;
                int r = DMTDeltaPLC.ReadDReg(2000, out result);
            
                if (r == -1)
                {
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        
                        red.Text = "正在重连..."; 
                        timer_heartbeat.Interval = TimeSpan.FromSeconds(10);

                        if (clcs > 1) RconnecPLC();
                        clcs++;
                    }));
                    return; 
                }
                else
                { 
                    clcs = 1; 
                    timer_heartbeat.Interval = TimeSpan.FromSeconds(1);
                }
                bool o = false;
              int i=  DMTDeltaPLC.ReadMReg(2,out o);
                if(i==1)
                {
                    if (!o)
                    {
                        start.Background = System.Windows.Media.Brushes.Green;
                        start.IsEnabled = true;
                        stop.Background = System.Windows.Media.Brushes.Gray;
                        stop.IsEnabled = false;
                        yy.Visibility = Visibility.Visible;
                        sz.Visibility = Visibility.Visible;
                    }
                }
                string wd2 = DMTDeltaPLC.ReadDReg(408, out result) == 0 ? result.ToString() : "0";//设定温度
                UIAction(() =>
                {
                     txt_sdwd.Text = (StringToFloat(wd2) / 10).ToString("#0.0") + "°C";

                });
               
            }
            catch (Exception ex) {
                UIAction(() =>
                {
                    red.Text = ex.Message;
                });

            }

        }
        //重置条码
        void CZTM()
        {
            //重置条码

            System.Drawing.Image image = BarcodeHelper.GenerateCZ("000000", 200, 50);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap
                                                                   // 下行,初始一个 ImageSource 作为 myImage 的Source
            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            bi.EndInit();
           // cztm.Source = bi; // done!
            ms.Close();

            tm1.Focus();
        }

        void LoadPlc()
        {
            loading();
               ip = ini.IniReadValue("TCPIP", "PLCIP");
            //string port = ConfigHelper.GetIni("PLCPort", "502");
            //DMTDeltaPLC.SetTCP(ip, StringToInt(port));
            //DMTDeltaPLC.IsTCP = true;
            //DMTDeltaPLC.SetSerial("COM3", 9600, 2, 2, 7);

            if (DMTDeltaPLC.ConnPLC(ip))
             {
            //    PLC.Background = System.Windows.Media.Brushes.Red;
            //    //ModBusTCPIPWrapper.Connect(ModBusTCPIPWrapper.Ipaddress, ModBusTCPIPWrapper.PortNum);
            //    busTcpClient.ConnectServer();
            //    if (ModBusTCPIPWrapper.IsConnected)
            //    {
            //        PLC.Background = System.Windows.Media.Brushes.Green;
                  LoadPLCData();
            //    }
            //}
            //else
            //{
            //    PLC.Background = System.Windows.Media.Brushes.Green;

             }
           
            loadingEnd();
        }
        void LoadPLCData()
        {
            double result = 0;
          
            string  aa=    DMTDeltaPLC.ReadDReg(14, out result) == 0 ? result.ToString() : "0";//出液重量
            txt_cy.Text =  getValueFromUnSigned(StringToInt(aa)).ToString();
             string wd= DMTDeltaPLC.ReadDReg(50, out result) == 0 ? result.ToString() : "0";//当前温度
            txt_dqwd.Text = (StringToFloat(wd) / 10).ToString("#0.0") + "°C";


            string wd2 = DMTDeltaPLC.ReadDReg(408, out result) == 0 ? result.ToString() : "0";//设定温度
            txt_sdwd.Text = (StringToFloat(wd2) / 10).ToString("#0.0") + "°C";

            txt_js.Text = DMTDeltaPLC.ReadDReg(100, out result) == 0 ? result.ToString() : "0";//加水
          
       
            txt_ddxx.Text = "";//订单信息

            p_hs.Value = per100();//毫升
            string D20  = DMTDeltaPLC.ReadDReg(20, out result) == 0 ? result.ToString() : "0";
            //D408.Text = DMTDeltaPLC.ReadDReg(408, out result) == 0 ? result.ToString() : "";
        }
        //条码扫描
        private void tm1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            //try { 
            //if (e.Key == Key.Enter)
            //{
            //    loading();
            //    try
            //    {
            //            //扫描清除M9
            //            int m9_1 = DMTDeltaPLC.SetMReg(9, false);

            //            LoadData(tm1.Text.Trim());
            //            tm1.Text = "";
            //            tm1.Focus();
            //    }
            //    catch (Exception ex)
            //    {
            //        PopMessageHelper.ShowMessage(tm1.Text +ex.Message + "！\r\n窗口关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            //    }
            //    loadingEnd();
            //}
            //  }     
            //catch (Exception ex)
            //{
            //    this._loading.Visibility = Visibility.Collapsed;
            //    PopMessageHelper.ShowMessage("提示:" + ex.Message + "！\r\n窗口关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            //}
}
        //开始m2
        private void btn_Start(object sender, TouchEventArgs e)
        {
             
            loading();
            int m96 = DMTDeltaPLC.SetMReg(2, true);
            if (m96 == 1)//操作成功
            {
                start.Background = System.Windows.Media.Brushes.Gray;
                start.IsEnabled = false;
                stop.Background = System.Windows.Media.Brushes.Red;
                stop.IsEnabled = true;
                yy.Visibility = Visibility.Hidden;
                sz.Visibility = Visibility.Hidden;
            }

            //bool o = false;
            //int m239 = DMTDeltaPLC.ReadMReg(2, out o);
            //if (m239 == 1)//操作成功
            //{
            //    int m96 = DMTDeltaPLC.SetMReg(2, !o);
            //    if (m96 == 1)//操作成功
            //    {

            //        if (o)
            //            start.Background = System.Windows.Media.Brushes.Green;
            //        else start.Background = System.Windows.Media.Brushes.Gray;


            //    }
            //}

          
            loadingEnd();
        }

        void reflashData()
        {
            try
            {
                double result = 0; 
                string wd = DMTDeltaPLC.ReadDReg(50, out result) == 0 ? result.ToString() : "0";//当前温度
                bool o1 = false;
               
                //更新，所有条件去除，只考虑M9
                    bool m9 = false;
                    int m9_ = DMTDeltaPLC.ReadMReg(9, out m9);  
               
                    if (m9)
                    {
                        int m9_1 = DMTDeltaPLC.SetMReg(9, false);
                    UIAction(() =>//
                    {
                       // tj();
                    });
                   }

             
                int m239 = DMTDeltaPLC.ReadMReg(4, out o1);
                if (m239 == 1)//操作成功
                {
                    string a = DMTDeltaPLC.ReadDReg(14, out result) == 0 ? result.ToString() : "0";//出液重量

                    UIAction(() =>
                    {
                        txt_cy.Text = getValueFromUnSigned(StringToInt(a)).ToString();
                    });

                    UIAction(() =>
                    {
                        txt_dqwd.Text = (StringToFloat(wd) / 10).ToString("#0.0") + "°C"; ;
                        p_hs.Value = per100();//毫升
                       
                    if (o1) txt_zt.SetResourceReference(TextBlock.TextProperty, "dzzcy");
                        //txt_zt.Text = "正在出液";
                        else txt_zt.SetResourceReference(TextBlock.TextProperty, "dddcy");
                    });


                 
                    //if (sftz)//是否停止，当是的时候，执行
                    //{
                    //   //// tips.Text = "1称重数量:;目标数量:" ;
                    //    if (!o1)//提交订单,且称重数值>=目标数值
                    //    {
                    //       // tips.Text = "2称重数量:;目标数量:";
                    //        sftz = false;
                         
                    //    }
                    //}
                 }
                bool o = false;
                int m205 = DMTDeltaPLC.ReadMReg(205, out o);
                if (m205 == 1 && o)//操作成功
                {
                    UIAction(() =>
                    {
                        cy.Visibility = Visibility.Visible;
                        txt_SDCY.Visibility = Visibility.Visible;
                        //刷新目标值
                        mbz();
                    });

                }
                else
                {
                    UIAction(() =>
                    {
                        cy.Visibility = Visibility.Collapsed;
                        txt_SDCY.Visibility = Visibility.Collapsed;
                    });
                }
                bool o2 = false;
                int m207 = DMTDeltaPLC.ReadMReg(207, out o2);
                if (m207 == 1 && o2)//操作成功
                {
                    UIAction(() =>
                    {
                        txt_sdwd.IsEnabled = true;
                    });

                }
                else
                {
                    UIAction(() =>
                    {
                        txt_sdwd.IsEnabled = false;
                    });
                }
               

            }
            catch (Exception ex)
            { }
        }
        //停止m1
        private void btn_Stop(object sender, TouchEventArgs e) {
            loading();
            timer.Stop();
            int m96 = DMTDeltaPLC.SetMReg(2, false);
            if (m96 == 1)//操作成功
            {
                start.Background = System.Windows.Media.Brushes.Green;
                start.IsEnabled = true;
                stop.Background = System.Windows.Media.Brushes.Gray;
                stop.IsEnabled = false;
                yy.Visibility = Visibility.Visible;
                sz.Visibility = Visibility.Visible;
            }
            //bool o = false;
            //int m239 = DMTDeltaPLC.ReadMReg(1, out o);
            //if (m239 == 1)//操作成功
            //{
            //    int m96 = DMTDeltaPLC.SetMReg(1, !o);
            //    if (m96 == 1)//操作成功
            //    {
            //        if (o)
            //                stop.Background = System.Windows.Media.Brushes.Green;
            //            else stop.Background = System.Windows.Media.Brushes.Gray;


            //    }
            //}
            loadingEnd();
        }
        //预约
        private void btn_yy(object sender, TouchEventArgs e) {
            this.aaa.IsOpen = false;
            this.ModalDialog.IsOpen = false;
            DilutionPLC_SelectDate ds = new DilutionPLC_SelectDate();
            ds.Width = 400;
            ds.Height = 300;
            ds.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            ds.Closing += Ds_Closing;
            ds.ShowDialog(); 
        }

        private void Ds_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if(publicclass.IsPreStart)
            {
                btn_Start(null, null);
            }
           
            publicclass.IsPreStart = false;
        }

        //设置
        private void btn_sz(object sender, TouchEventArgs e)
        {
            ShowModalDialog(true);
        }
        //加水
        private void btn_js(object sender, TouchEventArgs e)
        {

            if (txt_js.Text != "")
            {
                bool o = false;
                int ii = DMTDeltaPLC.ReadMReg(3, out o);


                int m96 = DMTDeltaPLC.SetMReg(3, !o);//加水开关M3 置1
                if (m96 == 1)//操作成功
                {
                    if(!o==true)
                    {
                       bool r = SendPLC32(StringToInt(txt_js.Text),101,100);
                            //DMTDeltaPLC.SetDReg(100, StringToInt(txt_js.Text));//加水量D100 32位整数
                       
                    }
                    
                }

            }
            else
            {
                tips.SetResourceReference(TextBlock.TextProperty, "ErrorPwd");
                tips2.SetResourceReference(TextBlock.TextProperty, "InfoTitle");
                ScannerApp.Common.AutoClosedMsgBox.Show(tips.Text, tips2.Text, 3000, MsgBoxStyle.BlueInfo_OK);
              //  ScannerApp.Common.AutoClosedMsgBox.Show("密码错误", "提示", 3000, MsgBoxStyle.BlueInfo_OK);

               // PopMessageHelper.ShowMessage("密码错误!!!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);
            }
           
        }
        //提交（POPUP）
        private void btn_tj(object sender, TouchEventArgs e)
        {
            if (publicclass.PopNum != "")
            {
                if (Type == "SDWD")
                {
                    if ((int)(StringToFloat(publicclass.PopNum)) > 40)
                    {
                        PopMessageHelper.ShowMessage("设定失败!温度不能超过40°", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

                        return;
                    }
                    int i = DMTDeltaPLC.SetDReg(408, (int)(StringToFloat(publicclass.PopNum) * 10));
                    if (i == 1)
                    {
                        txt_sdwd.Text = publicclass.PopNum + "°C";
                        aaa.IsOpen = false;
                        // ShowModalDialog(false);
                    }
                    else
                    {

                        PopMessageHelper.ShowMessage("设定失败!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

                    }
                }
                if (Type == "JS")
                {
                   bool a=  SendPLC32((int)(StringToFloat(publicclass.PopNum)),101,100);
                    if (a)
                    {
                        txt_js.Text = publicclass.PopNum ;
                        aaa.IsOpen = false;
                        // ShowModalDialog(false);
                    }
                    else
                    {

                        PopMessageHelper.ShowMessage("设定失败!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

                    }
                }
                else if(Type == "SDCY") {
                   // int i = DMTDeltaPLC.SetDReg(106, (int)(StringToFloat(publicclass.PopNum)));

                    bool a = SendPLC32((int)(StringToFloat(publicclass.PopNum)), 107, 106);
                    if (a)
                    {
                      //  if (i == 1)
                    //{
                        txt_SDCY.Text = publicclass.PopNum ;
                        aaa.IsOpen = false;
                        // ShowModalDialog(false);
                    }
                    else
                    {

                        PopMessageHelper.ShowMessage("设定失败!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

                    }
                } 

        }
            else
            {

                PopMessageHelper.ShowMessage("请设定一个有效温度值!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

            }
        }
        //设定温度
        private void _sdwd(object sender, TouchEventArgs e)
        {
            Type = "SDWD";
            aaa.IsOpen = true;
        }
        private void btn_numclose(object sender, TouchEventArgs e)
        {
            publicclass.PopNum = "0";
            aaa.IsOpen = false;
        }
      
        private void PLC_TouchDown(object sender, TouchEventArgs e)
        {
            RconnecPLC();

        }
        private void close_TouchDown(object sender, TouchEventArgs e)
        {
            tips.SetResourceReference(TextBlock.TextProperty, "oClose");
            MessageBoxResult result = System.Windows.MessageBox.Show(tips.Text, "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                Application.Current.Shutdown();
                Environment.Exit(0);
            }
         

        }
        //最小化
        private void  MouseLeftButtonmin(object sender, TouchEventArgs e)
        {

           
          
                WindowState= WindowState.Minimized;
            

            }
        //关机
        private void  MouseLeftButtonPower(object sender, TouchEventArgs e)
        {
            tips2.SetResourceReference(TextBlock.TextProperty, "oCloseComputer");
            MessageBoxResult result = System.Windows.MessageBox.Show(tips2.Text, "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                ProcessStartInfo ps = new ProcessStartInfo();
                ps.FileName = "shutdown.exe";
                ps.Arguments = "-s -t 1";
                Process.Start(ps);
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
          

            //PopMessageHelper.ShowMessage("关机" + "！\r\n窗口关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

        }

        //出液M4
        private void btn_CY(object sender, TouchEventArgs e)
        {
            bool o = false;
            int m205 = DMTDeltaPLC.ReadMReg(4, out o);
            if (m205 == 1)//操作成功
            {
                if (o) txt_SDCY.Background = Brushes.Red;
                else txt_SDCY.Background = Brushes.Green;

                int m96 = DMTDeltaPLC.SetMReg(4, !o);//设定出液量M4
                if (m96 == 1)//操作成功
                {
                }

            }
           
            

        }
        //出液
        private void cy_mlb(object sender, TouchEventArgs e)
        {
            Type = "SDCY";
            aaa.IsOpen = true;
        }

        private void js_mlb(object sender, TouchEventArgs e)
        {
            Type = "JS";
            aaa.IsOpen = true;
        }
        

        void RconnecPLC()
        {
            DMTDeltaPLC.DisConnPLC();
            PLC.Background = System.Windows.Media.Brushes.Red; 
            if (DMTDeltaPLC.ConnPLC(ip))
            { red.Text = "";
                PLC.Background = System.Windows.Media.Brushes.Green;
                LoadPLCData();
            } 
            loadingEnd();
        }

        void LoadData(string tm)
        {
            //不是重置条码，就不能扫描
            if (!cansacn&& tm1.Text.Trim() != "000000")
            {
                tm1.Text = "";
                tm1.Focus();
                return; 
            }
           
            if (tm.Length <= 1)
            {
                Tips("ErrorBarCode");
                return;
            }

            if (tm1.Text.Trim() == "000000")//6个0，重置条码
            {
                Clear();
                strTm1 = "";//清除
                cansacn = true;
                tm1.IsEnabled = true;
                tm1.Focus();
                return;
            }
         

            DataTable lsdt = sa.GetDataTable_collection_condition(tm, "dilution");
            if (lsdt == null)
            {
                Clear();
                Tips("ErrorNoOrder");
            }
            else
            {
                if (lsdt.Rows.Count <= 0)
                {
                    Clear();
                    Tips("ErrorNoOrder");
                }
                else
                {

                  
                    foreach (DataRow dr in lsdt.Rows)
                    {
                      
                        txt_ddxx.Text = dr["id"].ToString();
                        scfs.Text = dr["produceddosis"].ToString();
                        tjl.Text = dr["dosisvolume"].ToString();
                        xsbl.Text = dr["dilutionratio"].ToString(); //稀释比例
                        zjzs.Text = dr["totalspermsperdosis"].ToString(); //每份总精子
                        zl.Text = dr["totalfinalvolume"].ToString();
                        yjzl.Text = dr["ejaculatedvolume"].ToString();
                        dd.Text = dr["Serialnumber"].ToString();
                        zyd.Text = dr["id"].ToString(); ;
                       // kh.Text = dr["cus_name"].ToString();
                        cpmc.Text = dr["product_name"].ToString();
                        //ddsl.Text = dr["quantity"].ToString();
                        // dw.Text = dr["unit"].ToString();
                        //zd.Text = dr["DeviceName"].ToString();
                        //gwh.Text = dr["BoarName"].ToString();
                        mfrl.Text = dr["capacity"].ToString();
                        //D106 发送添加剂
                        if (dr["ejaculatedvolume"].ToString() == "")
                        { tips.SetResourceReference(TextBlock.TextProperty, "ErrorFix");
                           // tips.Text = "请验证分析数据是否有效！";
                            return; }
                        int yyzl = stringtoint(dr["ejaculatedvolume"].ToString());
                        double result = 0;
                        string a = DMTDeltaPLC.ReadDReg(14, out result) == 0 ? result.ToString() : "0";//出液重量
                        txt_SDCY.Text = dr["totalfinalvolume"].ToString();
                        if (yyzl > stringtoint(a) + 20 || yyzl < stringtoint(a) - 20)
                        {
                            tips.SetResourceReference(TextBlock.TextProperty, "ErrorMax");
                           // tips.Text = "出液重量和源液重量相差过大！";
                            return;//直接返回
                        }
                        else tips.Text = "";
                        sftz = true;

                        if (stringtoint(dr["totalfinalvolume"].ToString()) > 0)
                        {
                            bool at = SendPLC32(StringToInt(dr["totalfinalvolume"].ToString()), 107, 106);
                            if (at)
                            {
                              // int i = DMTDeltaPLC.SetDReg(106, StringToInt(dr["totalfinalvolume"].ToString()));
                            //if (i == 1)
                            //{
                                //加入判断
                             
                                int r = DMTDeltaPLC.ReadDReg(106, out result);

                                if (result == StringToInt(dr["totalfinalvolume"].ToString()))
                                {
                                    int m96 = DMTDeltaPLC.SetMReg(4, true);//M4 泵出
                                    if (m96 == 1)//操作成功
                                    {
                                        tm1.IsEnabled = false;
                                        cansacn = false;//所有流程对了，就可以设置不能扫描，除非重置或者结案
                                    }
                                    else
                                    {

                                        PopMessageHelper.ShowMessage("设定失败!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

                                    }
                                }
                                else
                                {

                                    PopMessageHelper.ShowMessage("发送总量不对，重新扫描!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

                                }

                            }
                            else
                            {

                                PopMessageHelper.ShowMessage("设定失败!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

                            }
                        }
                        else {
                            PopMessageHelper.ShowMessage("总量小于0，无法启动！\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);


                        }

                    }

                }

            }

        }

        int stringtoint(string a)
        {
            int i = 0;
            try {
                i = StringToInt(a);
            } catch { }
            return i;
        }

        private void tj()
        {
             
                    string msg = sa.Update_boar_collection_status("dilution", txt_ddxx.Text.Trim());
                    if (txt_ddxx.Text.Trim() != "" && msg == "")
                    {
                        // printBarCode();
                        string para = "{\"EventType\":\"种禽稀释提交\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + txt_ddxx.Text + "\",\"Log_Content\":\"" + "【稀释提交(状态)】 → 15\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                        string msglog = sa.Sys_log(para);
                        Clear();
                        strTm1 = "";
                cansacn = true;
                tm1.IsEnabled = true;
                Tips("SuccessDJ");
                //PopMessageHelper.ShowMessage("提交成功!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);
            }
            else
                    {
                Tips("ErrorNoOrder");
                // PopMessageHelper.ShowMessage("没有订单！\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);

            }



        }

        private void loading()
        {
            this._loading.Visibility = Visibility.Visible;
        }
        private void loadingEnd()
        {
            this._loading.Visibility = Visibility.Collapsed;
        }
        void Tips(string msg)
        {
            UIAction(() =>
            {
                tips2.SetResourceReference(TextBlock.TextProperty, msg);
                ScannerApp.Common.AutoClosedMsgBox.Show("提示:" + tips2.Text + "！\r\n3秒后窗口关闭...", "提示", 3000, MsgBoxStyle.BlueInfo_OK);

            }); 
            Logger.Instance.WriteLog(publicclass.UserName + "[稀释]" + msg, LogType.Error, "Dilution");
            tm1.Focus(); return;
        }

        void Clear()
        {
            txt_cy.Text = "0";//出液重量
            txt_dqwd.Text = "0";//当前温度
            txt_js.Text = "0";//加水
            txt_tz.Text = "0";//桶重
            txt_sdwd.Text = "0";//设定温度
           
            txt_ddxx.Text = "";//订单信息

            p_hs.Value = 0;//毫升

            yjzl.Text = "";//精原重量

            tm1.Text = "";
            zl.Text = "";//总量
            zjzs.Text = "";//总精子数
            xsbl.Text = "";//稀释比例
            tjl.Text = "";//添加剂
            scfs.Text = "";//生产份数


            dd.Text = "";
            zyd.Text = "";
            //kh.Text = "";
            cpmc.Text = "";
            //ddsl.Text = "";
            //dw.Text = "";
            //zd.Text = "";
            //gwh.Text = "";
            mfrl.Text = "";

        }

        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }
        //目标值刷新
        void mbz()
        {
            double result = 0;
            string hr = DMTDeltaPLC.ReadDReg(107, out result) == 0 ? result.ToString() : "0";//高位

            string lr = DMTDeltaPLC.ReadDReg(106, out result) == 0 ? result.ToString() : "0";//低位
            string h_two = Convert.ToString(StringToInt(hr), 2).PadLeft(16, '0');
            string l_two = Convert.ToString(StringToInt(lr), 2).PadLeft(16, '0');
            string tow = h_two + l_two;
            int ha = Convert.ToInt32(h_two, 2);
            int a = 0;
            if (ha > 0)//如果>65535（即高位有数据）
            {
                a = Convert.ToInt32(tow, 2);
            }
            else
            {//否则16位双字节
                a = getValueFromUnSigned(Convert.ToInt16(l_two, 2));
            }
            UIAction(() =>
            {
                txt_SDCY.Text = a.ToString();
            });
        }
        //等分100份
        int per100()
        {
            int i = 0;

            try {
                double result = 0;
                string hr = DMTDeltaPLC.ReadDReg(17, out result) == 0 ? result.ToString() : "0";//桶重高位

                string lr = DMTDeltaPLC.ReadDReg(16, out result) == 0 ? result.ToString() : "0";//桶重低位
                string h_two = Convert.ToString(StringToInt(hr), 2).PadLeft(16, '0');
                string l_two = Convert.ToString(StringToInt(lr), 2).PadLeft(16, '0');
                string tow = h_two + l_two;
                int ha= Convert.ToInt32(h_two, 2);
                int a = 0;
                if (h_two.Substring(1) == "1")//高位Bit31为1，则补码
                {
                    string hr_ = "", lr_ = "" ;
                    for (int hr1 = 0; hr1 < h_two.Length; hr1++)
                    {
                        if (h_two.Substring(hr1, 1) == "1") hr_ += "0"; else hr_ += "1";
                    }
                    for (int lr1 = 0; lr1 < l_two.Length; lr1++)
                    {
                        if (l_two.Substring(lr1, 1) == "1") lr_+= "0"; else lr_ += "1";
                    }
                    a = -Convert.ToInt32(BinaryStrAdd(hr_ + lr_,"1"), 2);
                }
                else
                {
                    a = Convert.ToInt32(tow, 2);
                }
                //if (ha > 0)//如果>65535（即高位有数据）
                //{
                //    //高位全部为1 则为负数
                //    if (ha == 65535)
                //    { a = -(Convert.ToInt32(l_two, 2)); }
                //    else
                //    a = Convert.ToInt32(tow, 2); 
                //}
                //else {//否则16位双字节
                //    a = (Convert.ToInt32(l_two, 2));
                //}
               
                UIAction(() =>
                {
                    txt_tz.Text = a.ToString();
                });
                string t = DMTDeltaPLC.ReadDReg(412, out result) == 0 ? result.ToString() : "0";//桶重高位

                 
                i = a / (StringToInt(t)*10);
                //if (aa > 100&&aa<1000)
                //{
                //    i = aa / 10;
                //}
                //if (aa > 1000 && aa < 10000)
                //{
                //    i = aa / 100;
                //}
            }
            catch { }
            return i;
        }
        //二进制加法
        static string BinaryStrAdd(string str1, string str2)
        {
            // Ignore Validation...

            string result = string.Empty;

            int len = 0;
            char[] ch1 = str1.Reverse().ToArray();
            char[] ch2 = str2.Reverse().ToArray();

            len = ch1.Length > ch2.Length ? ch1.Length : ch2.Length;
            byte[] b1 = new byte[len];
            byte[] b2 = new byte[len];
            byte[] b3 = new byte[len + 1];
            for (int i = 0; i < ch1.Length; i++)
            {
                b1[i] = Convert.ToByte(ch1[i].ToString());
            }

            for (int i = 0; i < ch2.Length; i++)
            {
                b2[i] = Convert.ToByte(ch2[i].ToString());
            }

            byte carry = 0;
            for (int i = 0; i < len; i++)
            {
                if (i != 0)
                {
                    if (carry == 1)
                    {
                        b3[i] = (byte)(b1[i] + b2[i] + carry);
                    }
                    else
                    {
                        b3[i] = (byte)(b1[i] + b2[i]);
                    }
                }
                else
                {
                    b3[i] = (byte)(b1[i] + b2[i]);
                }

                if (b3[i] == 2)
                {
                    b3[i] = 0;
                    carry = 1;
                }
                else if (b3[i] == 3)
                {
                    b3[i] = 1;
                    carry = 1;
                }
                else
                {
                    carry = 0;
                }
            }

            if (carry == 1)
            {
                b3[len] = 1;
            }

            StringBuilder sb = new StringBuilder();
            for (int i = b3.Length - 1; i >= 0; i--)
            {
                sb.Append(b3[i]);
            }

            result = sb.ToString();
            return result;
        }


        bool SendPLC32(int jss,int hight,int low)
        {
            //int jss = (int)(StringToFloat(publicclass.PopNum));
            string tow = Convert.ToString(jss, 2).PadLeft(32, '0');
            string h_two = tow.Substring(0, 16);
            string l_tow = tow.Substring(16, 16);
            int i = DMTDeltaPLC.SetDReg(low, Convert.ToInt32(l_tow, 2));
             int i2= DMTDeltaPLC.SetDReg(hight, Convert.ToInt32(h_two, 2));
            if (i == 1 && i2 == 1)
            {
                return true;
            }
            else return false;
        }

        //将双字节转换为有符号数。
        public int getValueFromUnSigned(int i)
        {
            string tow = Convert.ToString(i, 2).PadLeft(16, '0');
            int bHight = Convert.ToInt16(tow.Substring(0, 8), 2);
            int bLow = Convert.ToInt16(tow.Substring(8, 8), 2);
            if (bHight < 128)
                return ((bHight << 8) | bLow);
            else
                return (Int16)((bHight << 8) | bLow);
        }

        string Type = "SDWD";

        private void ShowModalDialog(bool bShow)
        {

            this.ModalDialog.IsOpen = bShow;
            // this.MainPanel.IsEnabled = !bShow;
        }
        private void Dlg_BtnOK_Click(object sender, TouchEventArgs e)
        {
            string pwd = ini.IniReadValue("密码设置", "PLC"); ;
            if (TxtBoxInput.Password == pwd)
            {
                ShowModalDialog(false);
                TxtBoxInput.Password = "";
             
                DilutionPLC_Setting ds = new DilutionPLC_Setting();
                ds.Width = 600;
                ds.Height = 600;
                ds.ShowDialog();
               
            }
            else
            {
                PopMessageHelper.ShowMessage("密码错误!!!\r\n窗口关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);
            }

        }
        private void Dlg_BtnClose_Click(object sender, TouchEventArgs e)
        {
            ShowModalDialog(false);

        }

        private void Yy_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }


        private void TextBlock_Click(object sender, TouchEventArgs e)
        {
            try
            {


                TextBlock btn = e.OriginalSource as TextBlock;
                if (btn.Name == "Back")
                {
                    TxtBoxInput.Password = TxtBoxInput.Password.Substring(0, TxtBoxInput.Password.Length - 1);
                }
                else
                {
                    TxtBoxInput.Password += btn.Text;
                }
                // publicclass.PopNum = TxtBoxInput.Text.Length == 0 ? "0" : TxtBoxInput.Text;
            }
            catch
            {
            }
        }


        private int StringToInt(string s)
        {
            int i = 0;
            try {
                i = int.Parse(s);
            } catch { }
            return i;
        }
        private float StringToFloat(string s)
        {
            float i = 0;
            try
            {
                i = float.Parse(s);
            }
            catch { }
            return i;
        }
    }
}
